const http = require('http');
const express = require('express')
const config = require('./config')

const app = express()

const expressSwagger = require('express-swagger-generator')(app);
expressSwagger({
    swaggerDefinition: {
        info: {
            description: 'node-server',
            title: 'node-server',
            version: '1.0.0',
        },
        host: 'localhost:1234',
        produces: [
            "application/json",
            "application/xml"
        ],
        schemes: ['http', 'https'],
    },
    basedir: __dirname, //app absolute path
    files: ['./routes/**/*.js'] //Path to the API handle folder
})
app.get('/', (req, res) => {
    res.redirect('/api-docs');
})


//允许前端 跨域请求
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, Content-Type, Access-Token");
    res.header("Access-Control-Allow-Methods", "*");
    res.header("Access-Control-Allow-Credentials", "true");
    /*
    处理cookie信息，如果有，并且不对每次请求都新开一个session
    axios.defaults.withCredentials = true;//每次请求，无论是否跨域，都带上cookie信息
    */
    next();
})

app.use('/user', require('./routes/user'))
var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(config.port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
    if (error.syscall !== 'listen') {
        throw error;
    }

    var bind = typeof port === 'string' ?
        'Pipe ' + port :
        'Port ' + port;

    // handle specific listen errors with friendly messages
    switch (error.code) {
        case 'EACCES':
            console.error(bind + ' requires elevated privileges');
            process.exit(1);
            break;
        case 'EADDRINUSE':
            console.error(bind + ' is already in use');
            process.exit(1);
            break;
        default:
            throw error;
    }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
    var addr = server.address();
    var bind = typeof addr === 'string' ?
        'pipe ' + addr :
        'port ' + addr.port;
    console.log('服务正在运行 http://localhost:' + addr.port);
    console.log('查看接口文档 http://localhost:' + addr.port + '/api-docs');
}